
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_book/config/application.dart';
import 'package:flutter_book/config/config.dart';
import 'package:flutter_book/data/model/base_response_model.dart';
import 'package:flutter_book/util/extensions/string_extensions.dart';

//超时时长 单位毫秒
const int _CONNECT_TIMEOUT = 10000;
const int _RECEIVE_TIMEOUT = 20000;


///服务端接口返回code
//成功
const int CODE_SUCCESS = 200;
//无法描述无法应对的服务端异常
const int CODE_SERVER_ERROR = 500;
//入参错误
const int CODE_PARAMETER_ERROR = 300;

//请求方法
const String METHOD_GET = "get";
const String METHOD_POST = "post";

Dio? _dioGet;
Dio? _dioPost;

//身份认证的类型
const int AUTH_TYPE_COMMON = 0;
const int AUTH_TYPE_NONE = 1;
const int AUTH_TYPE_TEMP = 2;

Future<T?> requestApi<T>(String url, Map<String, dynamic> queryParameters,
  {String requestMethod = METHOD_GET, CancelToken? token})async{

  BaseResponseModel responseModel = await _requestApi(url, queryParameters,requestMethod,token);

  if (responseModel.isSuccess) {
    return responseModel.data;
  } else {
    // "没有获取到了数据:$url,${queryParameters.toString()},$requestMethod".print;
    // "没有获取到了数据:${responseModel.message}".print;
    return null;
  }
}



//通用的请求api的方法，请在具体的子api中进行入参封装和结果处理 authType只在特定的接口中赋值
Future<BaseResponseModel> _requestApi(String path, Map<String, dynamic> queryParameters,
    [String requestMethod = METHOD_GET, CancelToken? token]) async {
  BaseResponseModel baseResponseModel=new BaseResponseModel();
  try {
    Response response;
    if (requestMethod == METHOD_GET) {
      setHeaders(getDioGetInstance());
      response = await getDioGetInstance().get(path, queryParameters: queryParameters, cancelToken: token);
    } else {
      setHeaders(getDioPostInstance());
      response = await getDioPostInstance().post(path, queryParameters: queryParameters, cancelToken: token);
    }
    baseResponseModel.data=response.data;
    baseResponseModel.isSuccess=true;
  } on DioError catch (e) {
    baseResponseModel.isSuccess=false;
    baseResponseModel.message=requestMethod+","+e.message;
  } catch (e) {
    baseResponseModel.isSuccess=false;
    baseResponseModel.message=requestMethod+","+"Unknown error";
  }
  return baseResponseModel;
}


void setHeaders(Dio dio, [BaseOptions? baseOptions]) {
  if (baseOptions == null) {
    dio.options.headers["aimy-drivers"] =
        "{\"os\":${Application.platform},\"clientVersion\":\"${AppConfig.version}\",\"channel\":0}";
    String auth = "Basic dXNlckFwcDpBaW15Rml0bmVzcw==";
    dio.options.headers["Authorization"] = auth;
    dio.options.headers["user-agent"] = "PostmanRuntime/7.26.8";
  } else {
    dio.options = baseOptions;
  }
}

//获取dio单例
Dio getDioPostInstance({bool isBaseUrl = false}) {
  if (_dioPost == null) {
    _dioPost = Dio();
    // if(isBaseUrl)
    //   _dioPost.options.baseUrl = AppConfig.getApiHost();
    _dioPost?.options.connectTimeout = _CONNECT_TIMEOUT;
    _dioPost?.options.receiveTimeout = _RECEIVE_TIMEOUT;
    //TODO 还需要更多详细的参数
    //设置拦截器用于打印log
    _dioPost?.interceptors.add(LogInterceptors());

    // (_dioPost.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
    //     (client) {
    //   //这一段是解决安卓https抓包的问题
    //   client.badCertificateCallback =
    //       (X509Certificate cert, String host, int port) {
    //     return Platform.isAndroid;
    //   };
    //   client.findProxy = (uri) {
    //     return "PROXY 192.168.10.117:8888";
    //   };
    // };
  }
  return _dioPost!;
}

Dio getDioGetInstance() {
  if (_dioGet == null) {
    _dioGet = Dio();
    _dioGet?.options.connectTimeout = _CONNECT_TIMEOUT;
    _dioGet?.options.receiveTimeout = _RECEIVE_TIMEOUT;
    //TODO 还需要更多详细的参数
    //设置拦截器用于打印log
    _dioGet?.interceptors.add(LogInterceptors());

    // (_dioGet.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
    //     (client) {
    //   //这一段是解决安卓https抓包的问题
    //   client.badCertificateCallback =
    //       (X509Certificate cert, String host, int port) {
    //     return Platform.isAndroid;
    //   };
    //   client.findProxy = (uri) {
    //     return "PROXY 192.168.10.117:8888";
    //   };
    // };
  }
  return _dioGet!;
}
//用于print log的拦截器
class LogInterceptors extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // "REQUEST[${options.headers}][${options.queryParameters}] ==> URL: ${options.baseUrl}${options.path}".print;
    // "REQUEST[${options.headers}][${options.queryParameters}] ==> URL: ${options.baseUrl}${options.path}".dialog;
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // "RESPONSE[${response.statusCode}][${response.data}] ==> URL: "
    //     "${response.requestOptions.baseUrl}${response.requestOptions.path}".print;
    // "RESPONSE[${response.statusCode}][${response.data}] ==> URL: "
    //     "${response.requestOptions.baseUrl}${response.requestOptions.path}".dialog;
    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    // "ERROR[${err.message}] ==> URL: ${err.requestOptions.baseUrl}${err.requestOptions.path}".print;
    // "ERROR[${err.message}] ==> URL: ${err.requestOptions.baseUrl}${err.requestOptions.path}".dialog;
    super.onError(err, handler);
  }
}